package cn.bdqn.service.impl;

import cn.bdqn.domain.Receipt;
import cn.bdqn.domain.SendFreight;
import cn.bdqn.mapper.ReceiptMapper;
import cn.bdqn.mapper.SendFreightMapper;
import cn.bdqn.service.ReceiptService;
import cn.bdqn.utils.result.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 回执单业务实现类
 * @author dkj
 */
@Service
public class ReceiptServiceImpl implements ReceiptService {


    @Autowired
    private ReceiptMapper receiptMapper;

    @Autowired
    private SendFreightMapper sendFreightMapper;

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @Override
    public Receipt queryByPrimaryKey(Integer id) {

        //根据id查询
        return receiptMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据发货单号模糊查询  分页
     * @param currentPage
     * @param pageSize
     * @param sendFreightNumber
     * @param state
     * @return
     */
    @Override
    public Page queryBySendFreightId(Integer currentPage,
                                              Integer pageSize,
                                              String sendFreightNumber,
                                              Integer state) {

        //开启分页
        PageHelper.startPage(currentPage>0?currentPage:1,pageSize);
        //模糊查询
        List<SendFreight> sendFreightList = sendFreightMapper.selectByLikeSendFreightNumber(sendFreightNumber);

        List<Receipt> receipts = new ArrayList<>();
        if (sendFreightList!=null&&sendFreightList.size()>0){
            //根据发货单号id和状态查询
            receipts = receiptMapper.selectBySendFreightId(sendFreightList, state);
        }else {
            receipts = receiptMapper.selectBySendFreightId(null, state);
        }
        //分页
        PageInfo<Receipt> receiptPageInfo = new PageInfo<>(receipts);
        //分页封装类
        Page page = new Page();
        //封装分页的数据
        page.setMenuList(receiptPageInfo.getList());
        //总页数
        page.setTotalRecord((int)receiptPageInfo.getTotal());
        //返回结果
        return page;
    }

    /**
     * 添加
     * @param receipt
     * @return
     */
    @Override
    public Receipt saveReceipt(Receipt receipt) {

        //根据发货单id查询
        SendFreight sendFreight = sendFreightMapper.selectByPrimaryKey(receipt.getSendFreightId());
        //赋值
        receipt.setSendFreight(sendFreight);
        //新增
        receiptMapper.insertReceipt(receipt);
        //返回结果
        return receipt;
    }

    /**
     * 更新
     * @param receipt
     */
    @Override
    public void updateReceipt(Receipt receipt) {

        //更新
        receiptMapper.updateReceipt(receipt);
    }
}
